import React from 'react';
import ReactApexChart from 'react-apexcharts';
import { ApexOptions } from 'apexcharts';

interface BubbleChartData {
  name: string;
  data: Array<{
    x: string;
    y: number;
    z: number;
  }>;
}

interface BubbleChartProps {
  data: BubbleChartData[];
  height?: number;
}

const BubbleChart: React.FC<BubbleChartProps> = ({ data, height = 520 }) => {
  // Constants moved from mock data
  const customerSegments = [
    { name: '年轻初级客户', value: 'young_primary' },
    { name: '中年积累期客户', value: 'middle_accumulation' },
    { name: '高净值中青年客户', value: 'high_net_worth_young' },
    { name: '稳健养老客户', value: 'stable_retirement' },
    { name: '激进专业客户', value: 'aggressive_professional' }
  ];

  const businessScenarioMap = {
    '自我介绍阶段': 1,
    '用户信息和偏好了解阶段': 2,
    '理念塑造和市场解读阶段': 3,
    '持仓诊断阶段': 4,
    '资产配置阶段': 5,
    '选品阶段': 6,
    '服务后跟进阶段': 7,
    '异议处理': 8
  };

  const businessScenarioLabels = [
    '自我介绍阶段',
    '用户信息和偏好了解阶段',
    '理念塑造和市场解读阶段',
    '持仓诊断阶段',
    '资产配置阶段',
    '选品阶段',
    '服务后跟进阶段',
    '异议处理'
  ];

  // 创建客户段到数值的映射
  const customerSegmentMap = customerSegments.reduce((map, segment, index) => {
    map[segment.name] = index + 1;
    return map;
  }, {} as Record<string, number>);

  // 转换数据格式：将x轴的字符串转换为数值
  const transformedData = data.map(series => ({
    ...series,
    data: series.data.map(point => ({
      x: customerSegmentMap[point.x] || 1, // 转换客户段名称为数值
      y: point.y,
      z: point.z,
      customerSegment: point.x, // 保留原始客户段名称用于tooltip
    }))
  }));

  const options: ApexOptions = {
    chart: {
      type: 'bubble',
      height,
      fontFamily: 'Inter, Noto Sans SC, sans-serif',
      toolbar: { show: false },
      animations: { 
        enabled: true, 
        speed: 800,
        animateGradually: {
          enabled: true,
          delay: 150
        }
      },
      zoom: {
        enabled: false
      },
      background: 'transparent'
    },
    plotOptions: {
      bubble: {
        minBubbleRadius: 8,   // 优化后的最小气泡半径
        maxBubbleRadius: 60,  // 优化后的最大气泡半径 (8-50px)
        zScaling: true        // 启用Z轴缩放
      }
    },
    dataLabels: { enabled: false },
    fill: { 
      opacity: 0.8,
      type: 'solid'
    },
    colors: ['#1d4ed8', '#3b82f6', '#93c5fd', '#9ca3af'],
    stroke: {
      width: 0
    },
    xaxis: {
      type: 'numeric',
      min: 0.8,
      max: customerSegments.length + 0.5,
      tickAmount: customerSegments.length,
      labels: {
        formatter: function (val: string) {
          const numVal = parseFloat(val);
          const roundedVal = Math.round(numVal);
          
          // 只在有效的客户段位置显示标签 (1-5)
          // 注意：ApexCharts可能会生成额外的刻度（如0,6等），这是正常的自动刻度行为
          if (roundedVal < 1 || roundedVal > customerSegments.length) {
            return ''; // 返回空字符串，不显示标签
          }
          
          const index = roundedVal - 1;
          const segmentName = customerSegments[index]?.name || '';
          
          return segmentName;
        },
        rotate: -30,
        rotateAlways: true,
        hideOverlappingLabels: false,
        trim: false,
        maxHeight: 160,
        style: {
          fontSize: '11px',
          fontWeight: 500,
          colors: '#6b7280'
        },
        offsetX: 20,  // 向右平移20像素
        offsetY: 5
      },
      axisBorder: { 
        show: true, 
        color: '#e5e7eb'
      },
      axisTicks: { 
        show: true, 
        color: '#e5e7eb'
      },
      tooltip: { enabled: false }
    },
    yaxis: {
      title: { 
        text: '业务场景',
        style: {
          fontSize: '14px',
          fontWeight: 600,
          color: '#374151'
        },
        offsetX: -10
      },
      
      labels: {
        formatter: function (val: number) {
          if (!val && val !== 0) return '';
          const roundedVal = Math.round(val);
          
          // 确保只显示1-8的标签
          if (roundedVal < 1 || roundedVal > 8) return '';
          
          const reverseYMap: { [key: number]: string } = {};
          for (const key in businessScenarioMap) {
            reverseYMap[businessScenarioMap[key as keyof typeof businessScenarioMap]] = key;
          }
          
          const fullLabel = reverseYMap[roundedVal] || '';
          // 优化标签显示 - 更好的缩短策略
          if (fullLabel.length > 8) {
            const parts = fullLabel.split('阶段');
            if (parts.length > 1) {
              return parts[0] + '...';
            }
            return fullLabel.substring(0, 6) + '...';
          }
          
          return fullLabel;
        },
        style: {
          fontSize: '11px',
          fontWeight: 500,
          colors: '#6b7280'
        },
        maxWidth: 120,
        offsetX: 50,
        offsetY: -20
      },
      min: 0.5,
      max: businessScenarioLabels.length + 0.5,
      tickAmount: businessScenarioLabels.length,
      showAlways: true,
      axisBorder: { 
        show: true, 
        color: '#e5e7eb'
      },
      axisTicks: { 
        show: true, 
        color: '#e5e7eb',
        offsetX: 0,
        offsetY: 0
      },
      tooltip: { enabled: false }
    },
    grid: {
      show: true,
      borderColor: '#f3f4f6',
      strokeDashArray: 3,
      position: 'back',
      xaxis: {
        lines: { show: true }
      },
      yaxis: {
        lines: { show: true }
      },
      padding: {
        top: 10,
        right: 30,
        bottom: 80,
        left: 160  // 增加左侧空间以确保y轴标签完整显示
      }
    },
    legend: {
      position: 'bottom',
      horizontalAlign: 'center',
      fontWeight: 500,
      offsetY: 10,
      show: true,
      labels: {
        colors: '#4b5563',
        useSeriesColors: false
      },
      itemMargin: {
        horizontal: 15,
        vertical: 8
      },
      fontSize: '12px'
    },
    tooltip: {
      custom: function({seriesIndex, dataPointIndex, w}: {seriesIndex: number, dataPointIndex: number, w: any}) {
        if (!w.globals.initialSeries[seriesIndex] || !w.globals.initialSeries[seriesIndex].data[dataPointIndex]) {
          return '';
        }
        const dataPoint = w.globals.initialSeries[seriesIndex].data[dataPointIndex];
        const seriesName = w.globals.seriesNames[seriesIndex];
        
        // 获取客户段名称
        const customerSegmentName = transformedData[seriesIndex].data[dataPointIndex].customerSegment;
        
        // 获取业务场景名称
        const reverseYMap: { [key: number]: string } = {};
        for (const key in businessScenarioMap) {
          reverseYMap[businessScenarioMap[key as keyof typeof businessScenarioMap]] = key;
        }
        const yLabel = reverseYMap[dataPoint.y] || '';

        return `<div style="background: #fff; border-radius: 8px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); border: 1px solid #e5e7eb; overflow: hidden;">` +
               `<div style="font-size: 14px; font-weight: 600; padding: 12px 16px; background: #f8fafc; border-bottom: 1px solid #e5e7eb; color: #1f2937;">${customerSegmentName}</div>` +
               `<div style="padding: 12px 16px;">` +
               `<div style="display: flex; align-items: center; margin-bottom: 8px;">` +
               `<span style="background-color: ${w.globals.colors[seriesIndex]}; width: 10px; height: 10px; border-radius: 50%; display: inline-block; margin-right: 10px;"></span>` +
               `<span style="color: #6b7280; font-size: 12px; margin-right: 8px;">业务场景:</span>` +
               `<span style="color: #1f2937; font-size: 12px; font-weight: 500;">${yLabel}</span>` +
               `</div>` +
               `<div style="margin-bottom: 8px;">` +
               `<span style="color: #6b7280; font-size: 12px; margin-right: 8px;">策略类型:</span>` +
               `<span style="color: #1f2937; font-size: 12px; font-weight: 500;">${seriesName}</span>` +
               `</div>` +
               `<div style="background: #f3f4f6; padding: 8px 12px; border-radius: 6px; margin-top: 8px;">` +
               `<span style="color: #6b7280; font-size: 12px; margin-right: 8px;">策略数量:</span>` +
               `<span style="color: #1f2937; font-size: 14px; font-weight: 700;">${dataPoint.z}</span>` +
               `</div>` +
               `</div>` +
               `</div>`;
      }
    },
    responsive: [
      {
        breakpoint: 768,
        options: {
          plotOptions: {
            bubble: {
              minBubbleRadius: 6,
              maxBubbleRadius: 35
            }
          },
          xaxis: {
            labels: {
              style: {
                fontSize: '10px'
              }
            }
          },
          yaxis: {
            labels: {
              style: {
                fontSize: '10px'
              }
            }
          },
          grid: {
            padding: {
              left: 120,  // 增加移动端左侧空间
              bottom: 80
            }
          }
        }
      }
    ]
  };

  return (
    <ReactApexChart 
      options={options} 
      series={transformedData} 
      type="bubble" 
      height={height} 
    />
  );
};

export default BubbleChart;